import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/auth/LoginView.vue'
import RegisterView from '../views/auth/RegisterView.vue'
import AssessmentListView from '../views/assessment/AssessmentListView.vue'
import AssessmentView from '../views/assessment/AssessmentView.vue'
import ResultView from '../views/assessment/ResultView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView,
    },
    {
      path: '/assessment',
      name: 'assessmentList',
      component: AssessmentListView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/assessment/:id',
      name: 'assessment',
      component: AssessmentView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/assessment/result/:id',
      name: 'result',
      component: ResultView,
      meta: {
        requiresAuth: true
      }
    }
  ],
})

// 路由守卫，检查用户是否登录
router.beforeEach((to, from, next) => {
  // 如果路由需要认证
  if (to.meta.requiresAuth) {
    // 检查localStorage中是否有token
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      // 没有登录，重定向到登录页
      next('/login')
    }
  } else {
    next()
  }
})

export default router
